package com.tongfusoft.document.web.controller.doc;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.tongfusoft.da.pagehelper.PageInfo;
import com.tongfusoft.document.doc.service.IPluploadService;
import com.tongfusoft.document.entity.BigFiles;
import com.tongfusoft.document.entity.DictionaryClass;
import com.tongfusoft.document.entity.FileFragments;
import com.tongfusoft.document.entity.UploadInfo;
import com.tongfusoft.document.entity.Users;
import com.tongfusoft.exception.ServiceException;
import com.tongfusoft.spring.web.core.controller.BaseController;
import com.tongfusoft.spring.web.core.controller.annotation.UrlDesc;
import com.tongfusoft.spring.web.core.data.DataTable;
import com.tongfusoft.spring.web.core.data.ResultModel;
import com.tongfusoft.utils.FileUtils;

@Controller
public class FileTransferResumeController extends BaseController {

	@Autowired
	public IPluploadService pluploadService;

	@RequestMapping("/fileTransferResume")
	@UrlDesc(value = "断点续传页")
	public String uploadBigFilePage(Model model) {

		model.addAttribute("mainPageKey", "fileTransferResume");
		model.addAttribute("mainPage", "doc/fileTransferResume");

		return "base";

	}
	
	@UrlDesc(value="我的大文件查询")
	@RequestMapping("/bigFile/query")
	@ResponseBody
	public DataTable<DictionaryClass> systemParamQuery(Model model, int length, int start, int draw) {

		DataTable rm = new DataTable();
		try {
			BigFiles bigfile = new BigFiles();
			bigfile.setCreatedBy(((Users)super.getUser()).getUserId());
			int pageIndex = (start / length)+1;
			if(length==-1){
				length = Integer.MAX_VALUE;
				
			}
			PageInfo pageInfo = this.pluploadService.bigFilesList(length, pageIndex, bigfile);

			rm.setDraw(draw);
			rm.setRecordsFiltered(pageInfo.getTotal());
			rm.setRecordsTotal(pageInfo.getTotal());
			rm.setData(pageInfo.getList());
		} catch (Exception e) {

			e.printStackTrace();
		}

		return rm;

	}
	
	
	@ResponseBody
	@RequestMapping(value = "/bigFile/isExist", method = RequestMethod.POST)
	@UrlDesc(value = "校验文件是否存在")
	public ResultModel bigFileUpload(String fileMd5) {
		ResultModel rm = new ResultModel();
		rm.setState("success");
		try {
			boolean md5Exist = this.pluploadService.isMd5Exist(fileMd5,(Users)super.getUser());
			if (md5Exist) {
				rm.setCode("exist");
			} else {
				rm.setCode("no_exist");
			}
		} catch (Exception e) {
			e.printStackTrace();
			rm.setCode("no_exist");
		}
		return rm;
	}
	@ResponseBody
	@RequestMapping(value = "/fileFragment/query", method = RequestMethod.POST)
	@UrlDesc(value = "大文件MD5")
	public ResultModel fileFragmentQuery(String fileMd5) {
		ResultModel rm = new ResultModel();
		rm.setState("success");
		try {
			List<FileFragments>  fragmentList = this.pluploadService.fragmentListByMd5(fileMd5,(Users)super.getUser());
			
			for(FileFragments fragment:fragmentList){
				
				fragment.setPath("");
				fragment.setPkValue("");
				
			}
			rm.setData(fragmentList);
		} catch (Exception e) {
			e.printStackTrace();
			rm.setCode("no_exist");
		}
		return rm;
	}
	@RequestMapping(value = "/fileTransferResume/upload")
	@ResponseBody
	@UrlDesc(value = "大文件上传服务")
	public ResultModel upload(UploadInfo uploadInfo, MultipartFile file) {

		String fileName=null;
		ResultModel rm = new ResultModel();
		rm.setState("success");
		try {
			
			if(StringUtils.isEmpty(uploadInfo.getMd5value())){
				rm.setCode("md5_null_error");
				rm.setState("error");
				return rm;
			}
			fileName = file.getOriginalFilename();
			uploadInfo.setFileName(file.getOriginalFilename());
			uploadInfo.setExt(FileUtils.getExtensionName(fileName));
			// 判断文件是否分块
			if (StringUtils.isNotEmpty(uploadInfo.getChunks()) && StringUtils.isNotEmpty(uploadInfo.getChunk())) {
				
				if(this.pluploadService.isFragmentsExist(uploadInfo.getMd5value(), uploadInfo.getChunk())){
					// 将文件分块保存到临时文件夹里，便于之后的合并文件
					this.pluploadService.saveFile(file, (Users) super.getUser(), uploadInfo);
				}
				// 验证所有分块是否上传成功，成功的话进行合并
				this.pluploadService.Uploaded(uploadInfo, (Users) super.getUser());
			} else {

				this.pluploadService.saveFile(file, (Users) super.getUser(), uploadInfo);
			}

		} catch (Exception ex) {
			ex.printStackTrace();
			rm.setState("error");
		}

		return rm;
	}
	@RequestMapping("/fileDel/{id}")
	@UrlDesc(value = "大文件删除")
	@ResponseBody
	public ResultModel fileDel(Model model,  @PathVariable("id") String id) {

		ResultModel rm = new ResultModel();
		try {
			rm.setState("success");
			this.pluploadService.deleteBigFile(id, (Users)super.getUser());
			
		} catch (ServiceException se) {

			rm.setState("error");
			rm.setCode(se.getMessage());

		} catch (Exception e) {
			rm.setState("error");
			e.printStackTrace();
		}
		return rm;

	}
}
